package com.itheima.service.db.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import com.itheima.vo.AnalysisSummaryVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

@DubboService
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    AnalysisByDayMapper analysisByDayMapper;

    @Autowired
    LogMapper logMapper;

    @Override
    public void saveOrUpdate() {
        //0.准备数据(今天,昨天)
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();//2022-11-08
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();//2022-11-07

        //1.查询今天有无记录
        LambdaQueryWrapper<AnalysisByDay> qw = new LambdaQueryWrapper<>();
        qw.eq(AnalysisByDay::getRecordDate, today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);

        if (analysisByDay == null) {
            //2.若无记录,封装对象,往表中存放记录
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(logMapper.findRegisterOrLoginCount(today, "0102"));
            analysisByDay.setNumActive(logMapper.findActiveCount(today));
            analysisByDay.setNumLogin(logMapper.findRegisterOrLoginCount(today, "0101"));
            analysisByDay.setNumRetention1d(logMapper.findRetention1d(today, yesterday));

            analysisByDayMapper.insert(analysisByDay);
        } else {
            //3.若有记录,封装对象,往表中更新记录
            analysisByDay.setNumRegistered(logMapper.findRegisterOrLoginCount(today, "0102"));
            analysisByDay.setNumActive(logMapper.findActiveCount(today));
            analysisByDay.setNumLogin(logMapper.findRegisterOrLoginCount(today, "0101"));
            analysisByDay.setNumRetention1d(logMapper.findRetention1d(today, yesterday));

            analysisByDayMapper.updateById(analysisByDay);
        }
    }

    @Override
    public AnalysisSummaryVo findSummary() {
        //1.准备数据
        Date date = new Date();
        String today = DateUtil.offsetDay(date, 0).toDateStr();
        String yesterday = DateUtil.offsetDay(date, -1).toDateStr();
        //过去7天
        String passWeek = DateUtil.offsetDay(date, -7).toDateStr();
        //过去1月
        String passMonth = DateUtil.offsetDay(date, -30).toDateStr();
        //获取今天的数据
        AnalysisByDay todayAnalysis = analysisByDayMapper.findByRecordDate(today);
        //获取昨天的数据
        AnalysisByDay yesterdayAnalysis = analysisByDayMapper.findByRecordDate(yesterday);

        //2.创建vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        //3.封装vo中9个数据
        //累计用户数 cumulativeUsers;
        vo.setCumulativeUsers(analysisByDayMapper.findUserTotalCount());

        //过去30天活跃用户数 activePassMonth;
        vo.setActivePassMonth(analysisByDayMapper.findActiveUserCountInPeriod(passMonth, yesterday));
        //过去7天活跃用户 activePassWeek;
        vo.setActivePassWeek(analysisByDayMapper.findActiveUserCountInPeriod(passWeek, yesterday));
        //今日新增用户数量  newUsersToday;
        vo.setNewUsersToday(todayAnalysis.getNumRegistered().longValue());
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌    newUsersTodayRate;
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(todayAnalysis.getNumRegistered(), yesterdayAnalysis.getNumRegistered()));
        //今日登录次数 loginTimesToday;
        vo.setLoginTimesToday(todayAnalysis.getNumLogin().longValue());
        //今日登录次数涨跌率，  loginTimesTodayRate;
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(todayAnalysis.getNumLogin(), yesterdayAnalysis.getNumLogin()));
        //今日活跃用户数量 activeUsersToday;
        vo.setActiveUsersToday(todayAnalysis.getNumActive().longValue());
        //今日活跃用户涨跌率， activeUsersTodayRate;
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(todayAnalysis.getNumActive(), yesterdayAnalysis.getNumActive()));

        //4.返回vo
        return vo;
    }

    @Override
    public Map findUsers(Integer type, Long sd, Long ed) {
        //sd=1611573846000L;//2021.1.25
        sd=1609500246000L;//2021.1.1
        ed=1612092246000L;//2021.1.31
        Date startDay = new Date(sd);
        Date endDay = new Date(ed);
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startDay);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDay);
        int day1 = startCalendar.get(Calendar.DAY_OF_YEAR);
        int day2 = endCalendar.get(Calendar.DAY_OF_YEAR);


        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i >= (day1 - day2); i--) {
            //得到过去一月的每一天
            String day = DateUtil.offsetDay(new Date(ed), i).toDateStr();
            System.out.println(day);
            //查询出当天的数据
            switch (type) {
                case 101://每天的新增用户
                    Map<String, Object> map2 = new HashMap<>();
                    AnalysisByDay analysis = analysisByDayMapper.findByRecordDate(day);
                    Integer amount = analysis.getNumRegistered();
                    map2.put("title", day);
                    map2.put("amount", amount);
                    list.add(map2);
                    break;
                case 102://每天的活跃用户
                    Map<String, Object> map3 = new HashMap<>();
                    AnalysisByDay analysis2 = analysisByDayMapper.findByRecordDate(day);
                    Integer amount2 = analysis2.getNumActive();
                    map3.put("title", day);
                    map3.put("amount", amount2);
                    list.add(map3);
                    break;
                case 103://每日留存用户
                    Map<String, Object> map4 = new HashMap<>();
                    AnalysisByDay analysis3 = analysisByDayMapper.findByRecordDate(day);
                    Integer amount3 = analysis3.getNumRetention1d();
                    map4.put("title", day);
                    map4.put("amount", amount3);
                    list.add(map4);
                    break;
            }

        }


        Map<String,Object> map5=new HashMap<>();
        map5.put("thisYear",list);
        map5.put("lastYear",null);
        return map5;
    }
}
